package com.zg.common.web.util.excel;

import cn.hutool.core.util.StrUtil;
import com.zg.common.web.socket.WebSocketServer;
import org.apache.poi.ss.usermodel.CellType;
import org.apache.poi.xssf.usermodel.XSSFCell;
import org.apache.poi.xssf.usermodel.XSSFRow;
import org.apache.poi.xssf.usermodel.XSSFSheet;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.springframework.stereotype.Component;

import java.io.InputStream;
import java.util.ArrayList;
import java.util.List;

/**
 * @author Zxb
 */
@Component
public class ExcelImportUtil {

	private static final String SUCCESS = "导入完成";
	private static final String FORMAT_ERROR = "格式出错，请按照要求的EXCEL格式导入数据";

	private ExcelImportUtil() {
		// 构造方法私有化
	}

	public static String getCellVal(XSSFRow row, int index) {
		XSSFCell cell = row.getCell(index);
		if (cell == null) {
			return "";
		}
		cell.setCellType(CellType.STRING);
		return cell == null ? "" : cell.getStringCellValue().trim();
	}

	public static List<String> importDataByExcel(String clientId, InputStream is, ExcelImportService callback) {
		List<String> errorList = new ArrayList<>();
		try {
			XSSFWorkbook book = new XSSFWorkbook(is);
			for (int index = 0; index < book.getNumberOfSheets(); index++) {
				XSSFSheet sheet = book.getSheetAt(index);
				int rows = sheet.getLastRowNum();
				for (int i = 1; i <= rows; i++) {
					if(StrUtil.isNotBlank(clientId)){
						WebSocketServer.sendMsg(clientId, "percent:" + (i * 100 / rows));
						WebSocketServer.sendMsg(clientId, "import:正在处理第" + i + "行数据");
					}
					if (callback.isRowHasData(sheet.getRow(i))) {
						String result = callback.importRow(sheet.getRow(i));
						if (!StrUtil.isEmpty(result) && !result.startsWith("success")) {
							errorList.add(result);
						}
					}
				}
			}
			book.close();
		} catch (Exception e) {
			e.printStackTrace();
			errorList.clear();
			errorList.add(FORMAT_ERROR);
		}
		errorList.add(SUCCESS);
		return errorList;
	}
}
